//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js')
Page({
  data: {
    nodata: 'none',
    isInspect: false,
    isPatrol: false,
    isSignIn: false,
    isPatrolInsp: false,
    isDutyWeek: false,
    isDutyWeek2: false,
    isSuperior: false, //教育局用户
    developing: false,
    inspectlist: [],
    features: null,
    loading: 1,
    stop:0,
    isElectricalsafetyShow: false,
    isElectricalsafetyShow2: false,
    isAceessDeviceShow: false,
    locationContent: "请在系统设置-应用权限管理中开启允许微信使用地理位置的开关",
    isAddressAndBlueteeRelation:false,
    isSmokeDevice:false,
    isUpdandDown:false,
    isFaceRecord:false,
    isSupervising:false,
    isSuddenSupervising:false,
    isNFCManager: false,
    hasEpidemicPunch: false,
    hasEpidemicQRcode: false,
    hsaQuestionForm: false,
    hsaSafetyInspect: false
  },

  onLoad: function(options) {
    wx.setNavigationBarTitle({
      title: app.globalData.department
    })
    wx.setNavigationBarColor({
      frontColor:"#DBD190"
    })
    this.setData({
      identity: app.globalData.identityId
    })

    if (app.globalData.identityId == "-1" || app.globalData.identityId == "-2") {
  
      app.globalData.features = ["0"];
      this.middle();
    } else {
      wx.request({
        url: app.userUrl + '/WeChat/permission/getWeChatFeatures',
        method: 'POST',
        data: {
          roleId: parseInt(app.globalData.identityId)
        },
        dataType: 'json',
        success: res => {
          app.globalData.features = res.data.key
        },
        complete: () => {
          this.middle();
        }
      })
    }

    if (1 == app.globalData.inspectModel) {
      wx.request({
        url: app.userUrl + '/WeChat/weChatSystem/getSchoolUUIDS',
        method: 'POST',
        data: app.globalData.departmentId,
        dataType: 'json',
        success: res => {
          this.setData({
            uuids: res.data.split(",")
          })
        }
      })
    }
    //蓝牙与地址关联设置
    if(app.globalData.identity == '管理员'){
      this.setData({
        isAddressAndBlueteeRelation:true
      })
    } else {
      this.setData({
        isAddressAndBlueteeRelation:false
      })
    }

    // 用电安全
    if(app.globalData.departmentId != 4){
      this.setData({
        isElectricalsafetyShow2:true
      })
    } else {
      this.setData({
        isElectricalsafetyShow2:false
      })
    }

    //门禁考勤、烟感设备、防撞柱
    wx.request({
      url: app.userUrl + '/WeChat/weChatSystem/isHasAceessDevice', 
      method: 'POST',  
      dataType: 'json',
      data: { 
        department : parseInt(app.globalData.departmentId) ,
        deviceType : 'upanddown'
      },
      success: res => {
        if(res.data == 'fail'){
          this.setData({
            isUpdandDown:true 
          })
        }
      }
    })
    wx.request({
      url: app.userUrl + '/WeChat/weChatSystem/isHasAceessDevice', 
      method: 'POST',  
      dataType: 'json', 
      data: {  
        department : parseInt(app.globalData.departmentId) ,
        deviceType : 'facerecord'
      },
      success: res => {
        if(res.data == 'fail'){
          this.setData({
            isFaceRecord:true 
          })
        }
      }
    })
    wx.request({
      url: app.userUrl + '/WeChat/weChatSystem/isHasAceessDevice', 
      method: 'POST',  
      dataType: 'json',
      data: { 
        department : parseInt(app.globalData.departmentId) ,
        deviceType : 'smoke'
      },
      success: res => {
        if(res.data == 'fail'){
          this.setData({
            isSmokeDevice:true 
          })
        }
      }
    })
    //值周
    wx.request({
      url: app.userUrl + '/WeChat/weChatSystem/isHasDutyRecoed', 
      method: 'POST',  
      dataType: 'json',
      data: { 
        schoolId : parseInt(app.globalData.departmentId) ,
      },
      success: res => {
        if(res.data == 'fail'){
          this.setData({
            isDutyWeek2:true 
          })
        }
      }
    })
  },

  
  getStatus(){
    wx.request({
      url: app.userUrl + '/WeChat/weChatSystem/judgeIsSupervising',
      method: "GET",
      data: {
        userId: app.globalData.userId
      },
      dataType: 'json',
      success: res => {
        if (res.data.length != 0) {
          app.globalData.isSupervising = true,
          app.globalData.superviseSchoolId = res.data[0].schoolId
          app.globalData.superviseSchoolName = res.data[0].name
          app.globalData.superviseId = res.data[0].id
          this.setData({
            isSupervising: true,
          })
        }
      }
    })
    //日常巡查
    wx.request({
      url: app.userUrl + '/WeChat/weChatSystem/judgeIsSuddenSupervising',
      method: "GET",
      data: {
        userId: app.globalData.userId
      },
      dataType: 'json',
      success: res => {
          if (res.data.length != 0) {
            app.globalData.isSuddenSupervising = true
            app.globalData.suddensuperviseSchoolName = res.data[0].schoolname
            app.globalData.suddensuperviseSchoolId = res.data[0].schoolId
            app.globalData.suddensuperviseId = res.data[0].id
            this.setData({
              isSuddenSupervising: true
            })
        }
      }
    })
  },

  onShow: function(options) {
    //巡查
    this.setData({
      isSupervising: app.globalData.isSupervising,
      isSuddenSupervising: app.globalData.isSuddenSupervising
    })
    this.middle()
    
  },

  middle: function() {
    if (app.globalData.identityId && app.globalData.features != null) {
      this.showIndex()
    }
  },

  onHide: function() {
      //缓存巡检所有数据
      
    this.setData({
      stop: 1
    })
    wx.stopBeaconDiscovery()
  },


  onUnload: function() {
    this.setData({
      stop: 1
    })
    wx.stopBeaconDiscovery()
    
  },

  toInspectItem: util.throttle(function(e) {

    // console.log("e", e);
    
    if (e.currentTarget.dataset.id != null) {
      wx.navigateTo({
        url: `/pages/inspectItem/inspectItem?id=${e.currentTarget.dataset.id}&idxcount=${this.data.idxcount}&categoryIdList=${this.data.categoryIdList}&currentcategoryId=${e.currentTarget.dataset.categoryid}&categoryName=${e.currentTarget.dataset.categoryname}`,
      })
    } else {
      wx.showToast({
        title: "暂无相关任务",
        image: '/images/lock.png'
      })
    }
  }),

  toSafetyScene: util.throttle(function(e) {
    wx.navigateTo({
      url: '/pages/safetysenceReport/safetysenceReport?id=' + e.currentTarget.dataset.id,
    })
  }),

  toEduInsp: util.throttle(function() {
    wx.navigateTo({
      url: '/pages/inspectItemEdu/inspectItemEdu',
    })
  }),

  toPatrolInsp: util.throttle(function() {
    // PC测试 START
    // wx.navigateTo({
    //   url: `/pages/inspectItemPatrol/inspectItemPatrol?bluetooth=35:10064`,
    // })
    // return
    // PC测试 END


    let that = this
    this.setData({
      stop: 0
    })
    if (wx.openBluetoothAdapter) {

      wx.showLoading({
        title: '正在搜索设备',
        mask: true
      })

      wx.openBluetoothAdapter({
        //开启蓝牙
        fail(res) {
          wx.showToast({
            title: "请开启蓝牙",
            image: "/images/warning.png",
            duration: 2000
          })
        },
        success(res) {

          wx.getLocation({
            type: 'wgs84',
            fail: (res) => {
              //不允许打开定位
              wx.hideLoading()
              wx.getSetting({
                success(res) {
                  //开启小程序内定位
                  if (res.authSetting["scope.userLocation"] == false) {
                    wx.showModal({
                      content: '请允许小程序使用地理位置功能！您可以在【我的】页面点击【设置】按钮快捷设置。',
                      confirmText: "去设置",
                      success: res => {
                        if (res.confirm) {
                          wx.switchTab({
                            url: '/pages/mine/mine'
                          })
                        }
                      }
                    })
                  } else {
                    //开启系统设置定位
                    wx.getSystemInfo({
                      success: res => {
                        if (res.platform == "ios") {
                          that.setData({
                            locationContent: "请在系统设置-微信里开启允许微信使用地理位置的开关"
                          })
                        }
                        wx.showModal({
                          title: '未允许使用地理位置',
                          content: that.data.locationContent,
                          showCancel: false
                        })
                      },
                      fail: res => {
                        wx.showModal({
                          title: '未允许使用地理位置',
                          content: that.data.locationContent,
                          showCancel: false
                        })
                      }
                    })
                  }

                }
              })
            },
            success: res => {
              //允许打开定位
              console.log(res)
              wx.startBeaconDiscovery({
                uuids: that.data.uuids,
                // uuids: ["00001803-494c-4f47-4943-544543480000"],
                success(res) {
                  let search = 0

                  function doSearch() {
                    search++
                    console.log(search)
                    if (!that.data.stop) {
                      if (search > 12) {
                        that.showModalOwn()
                      } else {
                        setTimeout(doSearch, 900)
                      }
                    }
                  }
                  doSearch()

                  wx.onBeaconUpdate(function(res) {
                    //加判断条件
                    console.log(res.beacons)
                    if (search <= 12) {
                      if (res.beacons.length) {
                        that.setData({
                          bluetooth: `${res.beacons[0].major}:${res.beacons[0].minor}`
                        })
                        that.setData({
                          stop: 1
                        })
                        wx.stopBeaconDiscovery()
                        wx.hideLoading()
                        wx.navigateTo({
                          url: `/pages/inspectItemPatrol/inspectItemPatrol?bluetooth=${that.data.bluetooth}`,
                        })
                      }

                    }
                  })
                },
                fail(res) {
                  that.showModalOwn()
                }
              })
            },
          })
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }

  }),

  showIndex: function() {
    //只有教师管理功能 或教师学生用户签到
    if (app.globalData.features == "35" || app.globalData.features== "0") {
      this.setData({
        loading: 0,
        isInspect: true
      })
      return
    }

    if (app.globalData.features.indexOf("37") != -1) {
      this.setData({
        isElectricalsafetyShow: true
      })
    } else {
      this.setData({
        isElectricalsafetyShow: false
      })
    }
    if (app.globalData.features.indexOf("50") != -1) {
      this.setData({
        isDutyWeek: true
      })
    } else {
      this.setData({
        isDutyWeek: false
      })
    }

    if (app.globalData.features.indexOf("42") != -1) {
      this.setData({
        isAceessDeviceShow: true
      }) 
    } else {
      this.setData({
        isAceessDeviceShow: false
      }) 
    }

    //教育局巡检员
    if (app.globalData.features.indexOf("36") != -1) {
      this.setData({
        isSuperior: true
      })
    } else {
      this.setData({
        isSuperior: false
      })
    }

    //NFC管理
    if(app.globalData.features.indexOf("121") != -1) {
      this.setData({
        isNFCManager: true
      })
    } else {
      this.setData({
        isNFCManager: false
      })
    }
     //防疫打卡
     if(app.globalData.features.indexOf("126") != -1) {
      this.setData({
        hasEpidemicPunch: true
      })
    } else {
      this.setData({
        hasEpidemicPunch: false
      })
    }
     //防疫通行码
     if(app.globalData.features.indexOf("127") != -1) {
      this.setData({
        hasEpidemicQRcode: true
      })
    } else {
      this.setData({
        hasEpidemicQRcode: false
      })
    }
     //问卷调查
     if(app.globalData.features.indexOf("128") != -1) {
      this.setData({
        hsaQuestionForm: true
      })
    } else {
      this.setData({
        hsaQuestionForm: false
      })
    }

    // 安全巡查
    if(app.globalData.features.indexOf("129") != -1) {
      this.setData({
        hsaSafetyInspect: true
      })
      // 判断是否有巡查任务正在进行
      this.getStatus()
    } else {
      this.setData({
        hsaSafetyInspect: false
      })
    }

    if (app.globalData.inspectModel != 1) {
      if (app.globalData.features.indexOf("33") != -1 || app.globalData.features.indexOf("34") != -1) {
        //巡检首页
        console.log("巡检")
        wx.request({
          url: app.userUrl + '/WeChat/weChatSystem/getInspectItemCategory',
          method: 'POST',
          data: {
            schoolId: app.globalData.departmentId,
            userId: app.globalData.userId,
            identityId: app.globalData.identityId
          },
          dataType: 'json',
          success: res => {
            if (res.data.length != 0) {
              let navData = []
              let idxcount = 0
              // idx判断显示该图片未配置，灰度显示
              let categoryIdList = []
              for (let i = 0; i < res.data.length; i++) {
                if (res.data[i].idx != null) {
                  navData[i] = res.data[i]
                  idxcount++
                  categoryIdList.push(res.data[i].undoneNum)
                }
                if (res.data[i].undoneNum > 99) {
                  res.data[i].undoneNum = '99+'
                }

                // console.log("categoryIdList", categoryIdList);
                
              }
              wx.setStorageSync('navData', navData)
              this.setData({
                // inspectlist: res.data,
                navData : navData ,
                idxcount: idxcount,
                categoryIdList: categoryIdList.join(","),
              })
            } else {
              this.setData({
                nodata: 'block'
              })
            }
          },
          fail: res => {
            wx.showToast({
              title: '网络异常！',
              image: '/images/warning.png'
            })
          },
          complete: res => {
            this.setData({
              loading: 0,
              isInspect: true
            })
          }
        })
      }else{
        this.setData({
          loading: 0,
          isInspect: true
        })
      }
    } else {
      console.log("~~~~~~~~~~~~~~~~~")
      if (app.globalData.features.indexOf("33") != -1) {
        this.setData({
          isPatrolInsp: true
        })
      }
      this.setData({
        loading: 0
      })
    }
  },

  startSignIn: util.throttle(function() {
    if ("-2" == app.globalData.identityId) {
      wx.navigateTo({
        url: '/pages/signInIndex/signInIndex',
      })
    } else {
      util.scanQRCode()
    }
  }),

  signInMa: util.throttle(function() {
    wx.navigateTo({
      url: '/pages/signInIndex/signInIndex',
    })
  }),

  signInStatistics: util.throttle(function() {
    // util.scanQRCode()
    
    wx.navigateTo({
      url: '/pages/signInStatistics/signInStatistics',
    })
  }),
  


  signdutyweeksatics: util.throttle(function() {
    if(this.data.isDutyWeek2){
      wx.showToast({
        title: '功能未激活~',
        mask:true, 
        image: '/images/warning.png'
      })
    }else{
      wx.navigateTo({
        url: '/pages/dutyweekItem/dutyweekItem',
      })
    }
  }),

  goToElectricalsafetyShow: function(e) {
    // let deviceName = encodeURI(encodeURI("体育馆"))
    if(this.data.isElectricalsafetyShow2){
      wx.showToast({
        title: '功能未激活~',
        mask:true, 
        image: '/images/warning.png'
      })
    }else{
      wx.navigateTo({ 
        // url: `/pages/webview/webview?schoolId=${app.globalData.departmentId}&src=http://tidukeji.cn/electricalsafety&type=electricalsafety&deviceName=${deviceName}&deviceId=355488020030634`,
        url: `/pages/webview/webview?src=${app.preUrl}/electricalsafety&type=electricalsafety&departmentId=${app.globalData.departmentId}`,
      })
    }
  },

  showModal:function(e){
      
      this.setData({
        modalName: "RadioModal"
        // forwardId: e.currentTarget.dataset.id
      })
  },
  goToAceessDevice: function (e){
    console.log(e.currentTarget)
    if (e.currentTarget.dataset.id === 'visit' || e.currentTarget.dataset.id ==='facerecord' ||
        this.data.isSmokeDevice ||  this.data.isUpdandDown){
        wx.showToast({
          title: '功能未激活~',
          mask:true,
          image: '/images/warning.png'
        })
    }else{
      wx.navigateTo({
        // url: `/pages/webview/webview?schoolId=${app.globalData.departmentId}&src=http://tidukeji.cn/electricalsafety&type=electricalsafety&deviceName=${deviceName}&deviceId=355488020030634`,
        url: `/pages/webview/webview?src=${app.preUrl}&type=accessDevice&departmentId=${app.globalData.departmentId}&deviceType=${e.currentTarget.dataset.id}`,
      })
    }

  },

  hideModal(e) {
      this.setData({
        modalName: null
      })
    },

  showModalOwn: function() {
    let that = this
    wx.hideLoading()
    wx.stopBeaconDiscovery()
    wx.showModal({
      title: "提示",
      content: "请确保您已到达巡检地点！",
      showCancel: false
    })
  },
  
  //新增道闸门禁---进去记录查询
  goToInOutRecordQuery: function (e){
    console.log(e.currentTarget)
    if (this.data.isFaceRecord){
      wx.showToast({
        title: '功能未激活~',
        mask:true,
        image: '/images/warning.png'
      })
    }else{
      wx.navigateTo({
        url: `/subpages/pages/inoutrecordQuery/inoutrecordQuery`,
      })
    }
  },
  //新增安全排名
  goToSecurityRank: function(e) {
      wx.navigateTo({ 
        url: `/pages/webview/webview?src=${app.preUrl}&type=securityRank&departmentId=${app.globalData.departmentId}`,
      })
  },

  //新增进度查询
  goToProgressRequiry: function(e) {
      wx.navigateTo({ 
        url: `/pages/webview/webview?src=${app.preUrl}&type=progressRequiry&departmentId=${app.globalData.departmentId}`,
      })
  },

  //跳转nfc感应界面
  toNFCPage:function(e){
    wx.navigateTo({
      url: `/subpages/pages/nfcResponse/nfcResponse`,
    })
  },

    //跳转nfc感应界面
    toDeviceAndAddressRelation:function(e){
      wx.navigateTo({
        url: `/subpages/pages/deviceAndAddressSetting/deviceAndAddressSetting`,
      })
    },
    //跳转每日打卡
    goToEpidemicPunch:function(e){
        wx.navigateTo({
          url: '/pages/epidemicPunch/epidemicPunch',
        })
    },
    goToEpidemicQRcode:function(e){
        wx.navigateTo({
          url: '/pages/epidemicQRcode/epidemicQRcode',
        })
    },
    //跳转问卷调查
    goToquestionNaire:function(e){
        wx.navigateTo({
          url: '/pages/questionForm/questionForm',
        })
    },

    goToRegularSupervise:function(e){
      if (app.globalData.isSuddenSupervising){
        wx.showToast({
          title: '当前已有巡查任务进行中...',
          icon: 'none'
        })
      }else{
      wx.navigateTo({
        url: `/subpages/pages/regularsupervise/regularsupervise`,
      })
    }
    },

    goToSuddenSupervise:function(e) {
      if (app.globalData.isSupervising){
        wx.showToast({
          title: '当前已有巡查任务进行中...',
          icon: 'none'
        })
      }else{
      wx.navigateTo({
        url: `/subpages/pages/suddensupervise/suddensupervise`,
      })
    }
    }
})